package com.example.myapplication3.nev;

import android.util.Log;

import com.example.myapplication3.api.ServiceApi;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpManagerLiss {
    private static HttpManagerLiss instance;
    public static HttpManagerLiss getInstance(){
        if(instance==null){
            synchronized (HttpManagerLiss.class){
                if(instance==null){
                    instance=new HttpManagerLiss();
                }
            }
        }
        return instance;
    }

    private ServiceApi serviceApi;


    private Retrofit getRetrofit(){
        Retrofit retrofit = new Retrofit.Builder().baseUrl(ServiceApi.URL_1)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return  retrofit;
    }

    private OkHttpClient getOkHttpClient(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new LoggingInterceptor())
                .addInterceptor(new HeaderInterceptor())
                .build();
        return okHttpClient;
    }

    static  class LoggingInterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.e("TAG", "intercept: "+request.newBuilder().toString() );
            return chain.proceed(request);
        }
    }

    static class HeaderInterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder()
                    .addHeader("Authorization", "APPCODE 964e16aa1ae944e9828e87b8b9fbd30a")
                    .build();
            return chain.proceed(request);
        }
    }


    public ServiceApi getService(){
        if(serviceApi==null){
            serviceApi=getRetrofit().create(ServiceApi.class);
        }
        return serviceApi;
    }
}
